package wpwork.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import wpwork.base.ActionResult;;
import wpwork.base.service.SuperServiceImpl;
import wpwork.entity.GpsInfoEntity;
import wpwork.entity.KshGroupEntity;
import wpwork.entity.UserGroupRelationEntity;
import wpwork.exception.DataException;
import wpwork.mapper.KshGroupTableMapper;
import wpwork.mapper.UserGroupRelationMapper;
import wpwork.model.*;
import wpwork.permission.entity.UserEntity;
import wpwork.permission.service.UserService;
import wpwork.service.KshGroupService;
import wpwork.util.UploaderUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class KshGroupServiceImpl extends SuperServiceImpl<KshGroupTableMapper, KshGroupEntity> implements KshGroupService {

    @Autowired
    private UserGroupRelationMapper userGroupRelationMapper;

    @Autowired
    private KshGroupTableMapper groupPersonMapper;


    @Override
    public List<GroupOrPersonDTO> getGroupAndPersonList() {
        return groupPersonMapper.selectGroupAndPersonList();
    }

    @Override
    public List<PersonByGroupDTO> selectPersonAndGroupName() {
        return groupPersonMapper.selectPersonAndGroupName();
    }



    @Override
    public List<KshGroupEntity> getGroupTree() {
        try {
            List<KshGroupEntity> allGroups = baseMapper.selectAllGroups();
            System.out.println("查询到的分组数量: {}"+allGroups.size());

            if (allGroups.isEmpty()) {
                System.out.println("未找到任何分组数据");
                return new ArrayList<>();
            }

            // 检查数据是否正确映射
            for (int i = 0; i < allGroups.size(); i++) {
                KshGroupEntity group = allGroups.get(i);
                System.out.println("分组 {}: id={}, name={}, parentId={}"+ i+ group.getId()+ group.getName()+group.getParentId());
                if (group == null) {
                    log.error("发现 null 分组对象，索引: {}"+ i);
                }
            }

            List<KshGroupEntity> tree = buildGroupTree(allGroups);
            System.out.println("构建树形结构完成，根节点数量: {}"+ tree.size());
            return tree;
        } catch (Exception e) {
            log.error("获取分组树失败", e);
            throw new RuntimeException("获取分组树失败: " + e.getMessage(), e);
        }
    }

    private List<KshGroupEntity> buildGroupTree(List<KshGroupEntity> groups) {
        // 过滤掉 null 元素
        List<KshGroupEntity> validGroups = groups.stream()
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        Map<Long, KshGroupEntity> groupMap = validGroups.stream()
                .collect(Collectors.toMap(KshGroupEntity::getId, Function.identity()));

        List<KshGroupEntity> rootGroups = new ArrayList<>();

        for (KshGroupEntity group : validGroups) {
            setParentName(group, groupMap);
        }

        for (KshGroupEntity group : validGroups) {
            Long parentId = group.getParentId();
            if (parentId == null || parentId == 0 || !groupMap.containsKey(parentId)) {
                rootGroups.add(group);
            } else {
                KshGroupEntity parent = groupMap.get(parentId);
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(group);
                }
            }
        }

        // 排序
        rootGroups.sort(Comparator.comparing(KshGroupEntity::getSortOrder));
        for (KshGroupEntity group : validGroups) {
            if (group.getChildren() != null) {
                group.getChildren().sort(Comparator.comparing(KshGroupEntity::getSortOrder));
            }
        }

        return rootGroups;
    }

    /**
     * 设置分组的父分组名称
     */
    private void setParentName(KshGroupEntity group, Map<Long, KshGroupEntity> groupMap) {
        Long parentId = group.getParentId();
        if (parentId != null && parentId > 0) {
            KshGroupEntity parent = groupMap.get(parentId);
            if (parent != null) {
                group.setParentName(parent.getName());
            } else {
                group.setParentName("未知父分组");
            }
        } else {
            group.setParentName("根分组");
        }
    }

    @Override
    public ActionResult createGroup(KshGroupEntity group) {
        try {
            // 检查编码是否重复
            LambdaQueryWrapper<KshGroupEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(KshGroupEntity::getCode, group.getCode())
                    .eq(KshGroupEntity::getDeleted, false);
            if (baseMapper.selectCount(queryWrapper) > 0) {
                return ActionResult.fail("分组编码已存在");
            }

            // 设置层级和路径
            if (group.getParentId() != null && group.getParentId() > 0) {
                KshGroupEntity parent = baseMapper.selectById(group.getParentId());
                if (parent == null) {
                    return ActionResult.fail("父分组不存在");
                }
                group.setLevel(parent.getLevel() + 1);
                group.setPath(parent.getPath() + parent.getId() + "/");
            } else {
                group.setLevel(1);
                group.setPath("/");
            }

            group.setDeleted(false);
            group.setCreatedTime(LocalDateTime.now());
            baseMapper.insert(group);

            return ActionResult.success("创建分组成功");
        } catch (Exception e) {
            return ActionResult.fail("创建分组失败: " + e.getMessage());
        }
    }

    @Override
    public ActionResult updateGroup(KshGroupEntity group) {
        try {
            // 检查编码是否重复（排除自身）
            LambdaQueryWrapper<KshGroupEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(KshGroupEntity::getCode, group.getCode())
                    .ne(KshGroupEntity::getId, group.getId())
                    .eq(KshGroupEntity::getDeleted, false);
            if (baseMapper.selectCount(queryWrapper) > 0) {
                return ActionResult.fail("分组编码已存在");
            }

            group.setUpdatedTime(LocalDateTime.now());
            baseMapper.updateById(group);

            return ActionResult.success("更新分组成功");
        } catch (Exception e) {
            return ActionResult.fail("更新分组失败: " + e.getMessage());
        }
    }

    @Override
    public ActionResult deleteGroup(Long id) {
        try {
            // 检查是否有子分组
            List<KshGroupEntity> children = baseMapper.selectByParentId(id);
            if (!children.isEmpty()) {
                return ActionResult.fail("请先删除子分组");
            }

            // 检查是否有用户绑定
            List<UserGroupRelationEntity> relations = userGroupRelationMapper.selectByGroupId(id);
            if (!relations.isEmpty()) {
                return ActionResult.fail("请先解除分组下的用户绑定");
            }

            baseMapper.logicDeleteById(id);
            return ActionResult.success("删除分组成功");
        } catch (Exception e) {
            return ActionResult.fail("删除分组失败: " + e.getMessage());
        }
    }

    @Override
    public ActionResult bindUsersToGroup(Long groupId, List<String> userIds) {
        try {
            KshGroupEntity group = baseMapper.selectById(groupId);
            if (group == null || group.getDeleted()) {
                return ActionResult.fail("分组不存在");
            }

            for (String userId : userIds) {
                if (!userGroupRelationMapper.existsByUserIdAndGroupId(userId, groupId)) {
                    UserGroupRelationEntity relation = new UserGroupRelationEntity();
                    relation.setUserId(userId);
                    relation.setGroupId(groupId);
                    relation.setCreatedBy(getCurrentUserId());
                    relation.setCreatedTime(LocalDateTime.now());
                    userGroupRelationMapper.insert(relation);
                }
            }

            return ActionResult.success("绑定用户成功");
        } catch (Exception e) {
            return ActionResult.fail("绑定用户失败: " + e.getMessage());
        }
    }

    @Override
    public ActionResult unbindUsersFromGroup(Long groupId, List<String> userIds) {
        try {
            for (String userId : userIds) {
                userGroupRelationMapper.deleteByUserIdAndGroupId(userId, groupId);
            }
            return ActionResult.success("解绑用户成功");
        } catch (Exception e) {
            return ActionResult.fail("解绑用户失败: " + e.getMessage());
        }
    }

    @Override
    public List<String> getGroupUserIds(Long groupId) {
        return userGroupRelationMapper.selectUserIdsByGroupId(groupId);
    }

    @Override
    public List<Long> getUserGroupIds(String userId) {
        return userGroupRelationMapper.selectGroupIdsByUserId(userId);
    }

    private Long getCurrentUserId() {
        // 根据你的认证系统实现获取当前用户ID
        // 示例：从SecurityContext或ThreadLocal中获取
        return 1L;
    }

    @Autowired
    private UserService userService;

    @Override
    public List<GroupUserTreeVO> getGroupTreeWithUsers() {
        // 1. 获取所有分组
        List<KshGroupEntity> allGroups = baseMapper.selectList(
                new LambdaQueryWrapper<KshGroupEntity>()
                        .eq(KshGroupEntity::getDeleted, false)
                        .orderByAsc(KshGroupEntity::getSortOrder)
                        .orderByAsc(KshGroupEntity::getId)
        );

        // 2. 构建分组树结构并同时过滤
        List<GroupUserTreeVO> groupTree = buildAndFilterGroupTreeWithUsers(allGroups);

        return groupTree;
    }

    /**
     * 构建分组树的同时进行过滤
     */
    private List<GroupUserTreeVO> buildAndFilterGroupTreeWithUsers(List<KshGroupEntity> groups) {
        // 过滤掉 null 元素
        List<KshGroupEntity> validGroups = groups.stream()
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        // 创建 ID 到分组的映射
        Map<Long, GroupUserTreeVO> groupMap = new HashMap<>();
        List<GroupUserTreeVO> groupVOs = new ArrayList<>();

        // 转换实体为VO，并设置基础信息
        for (KshGroupEntity group : validGroups) {
            GroupUserTreeVO groupVO = convertToGroupVO(group);
            groupMap.put(group.getId(), groupVO);
            groupVOs.add(groupVO);
        }

        // 构建树形结构并获取用户信息
        List<GroupUserTreeVO> rootGroups = new ArrayList<>();
        for (GroupUserTreeVO groupVO : groupVOs) {
            Long parentId = groupVO.getParentId();

            // 设置 parentName
            if (parentId != null && parentId > 0) {
                GroupUserTreeVO parent = groupMap.get(parentId);
                if (parent != null) {
                    groupVO.setParentName(parent.getName());
                }
            }

            // 构建树形结构
            if (parentId == null || parentId == 0 || !groupMap.containsKey(parentId)) {
                rootGroups.add(groupVO);
            } else {
                GroupUserTreeVO parent = groupMap.get(parentId);
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(groupVO);
                }
            }
        }

        // 第三步：为每个分组获取用户信息并同时过滤
        List<GroupUserTreeVO> filteredRootGroups = new ArrayList<>();
        for (GroupUserTreeVO rootGroup : rootGroups) {
            GroupUserTreeVO filteredGroup = populateUsersAndFilter(rootGroup);
            if (filteredGroup != null) {
                filteredRootGroups.add(filteredGroup);
            }
        }

        // 排序
        filteredRootGroups.sort(Comparator.comparing(GroupUserTreeVO::getSortOrder));
        sortGroupTree(filteredRootGroups);

        return filteredRootGroups;
    }

    /**
     * 递归地为分组填充用户信息并过滤
     */
    private GroupUserTreeVO populateUsersAndFilter(GroupUserTreeVO group) {
        if (group == null) {
            return null;
        }

        // 递归处理子分组
        List<GroupUserTreeVO> filteredChildren = new ArrayList<>();
        if (group.getChildren() != null) {
            for (GroupUserTreeVO child : group.getChildren()) {
                GroupUserTreeVO filteredChild = populateUsersAndFilter(child);
                if (filteredChild != null) {
                    filteredChildren.add(filteredChild);
                }
            }
        }

        // 获取当前分组的用户
        List<UserInfoVO> users = getGroupUsersWithDetails(Long.valueOf(group.getId()));
        group.setUsers(users);
        group.setUserCount(users.size());
//        group.setOnlineCount((int) users.stream().filter(UserInfoVO::getOnline).count());

        // 设置过滤后的子分组
        group.setChildren(filteredChildren);

        // 检查是否应该保留该分组
        boolean hasDirectUsers = !users.isEmpty();
        boolean hasChildrenWithUsers = !filteredChildren.isEmpty();

        // 如果有直接用户或子分组有用户，则保留该分组
        if (hasDirectUsers || hasChildrenWithUsers) {
            // 更新用户统计信息（包括子分组的用户）
            if (hasChildrenWithUsers) {
                int totalUserCount = users.size();
//                int totalOnlineCount = (int) users.stream().filter(UserInfoVO::getOnline).count();

                for (GroupUserTreeVO child : filteredChildren) {
                    totalUserCount += child.getUserCount();
//                    totalOnlineCount += child.getOnlineCount();
                }

                group.setUserCount(totalUserCount);
//                group.setOnlineCount(totalOnlineCount);
            }

            return group;
        }

        // 没有用户且没有有用户的子分组，过滤掉
        return null;
    }

    private GroupUserTreeVO convertToGroupVO(KshGroupEntity group) {
        GroupUserTreeVO vo = new GroupUserTreeVO();
        vo.setId(String.valueOf(group.getId()));
        vo.setName(group.getName());
        vo.setCode(group.getCode());
        vo.setParentId(group.getParentId());
        vo.setLevel(group.getLevel());
        vo.setPath(group.getPath());
        vo.setDescription(group.getDescription());
        vo.setSortOrder(group.getSortOrder());
        return vo;
    }

    private List<UserInfoVO> getGroupUsersWithDetails(Long groupId) {
        // 获取分组下的用户ID列表
        List<String> userIds = userGroupRelationMapper.selectUserIdsByGroupId(groupId);

        if (userIds.isEmpty()) {
            return new ArrayList<>();
        }

        // 获取用户详情
        List<UserInfoVO> userVOs = new ArrayList<>();
        for (String userId : userIds) {
            try {
                UserInfoVO userVO = getUserSimpleInfo(userId);
                if (userVO != null) {
                    userVOs.add(userVO);
                }
            } catch (Exception e) {
                // 继续处理其他用户，不因为单个用户失败而影响整个分组
            }
        }

        return userVOs;
    }

    private UserInfoVO getUserSimpleInfo(String userId) throws DataException {
        // 使用你现有的获取用户详情的方法
        UserEntity userEntity = userService.getInfo(userId);
        if (userEntity == null) {
            return null;
        }

        UserInfoVO userVO = new UserInfoVO();
        userVO.setId(userEntity.getId());
        userVO.setRealName(userEntity.getRealName());
        userVO.setAccount(userEntity.getAccount());
        userVO.setMobilePhone(userEntity.getMobilePhone());
        userVO.setHeadIcon(UploaderUtil.uploaderImg(userEntity.getHeadIcon()));




        // 设置在线状态（需要根据你的业务逻辑实现）
//        userVO.setOnline(checkUserOnline(userId));

        // 设置最后上报时间（需要根据你的业务逻辑实现）
//        userVO.setLastReportTime(getLastReportTime(userId));

        return userVO;
    }


    

    private void sortGroupTree(List<GroupUserTreeVO> groups) {
        if (groups == null) return;

        groups.sort(Comparator.comparing(GroupUserTreeVO::getSortOrder));

        for (GroupUserTreeVO group : groups) {
            if (group.getChildren() != null) {
                sortGroupTree(group.getChildren());
            }
//            if (group.getUsers() != null) {
//                group.getUsers().sort(Comparator.comparing(UserInfoVO::getRealName));
//            }
        }
    }

}
